<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Venturecraft\Revisionable\RevisionableTrait;

class Category extends Model
{
    // For admin log
    use RevisionableTrait;
    protected $keepRevisionOf = [
        'deleted_at'
    ];
    use SoftDeletes;

    protected $fillable = [];

    public function topics($filter)
    {
        return $this->hasMany('App\Models\Topic')->getTopicsWithFilter($filter);
    }

    public function subCategories()
    {
        return $this->hasMany('App\Models\Category', 'parent_id', 'id');
    }

    /**
     * 返回二层树结构的分类数组
     *
     * @param bool $toJson
     *
     * @return array|string
     */
    public static function tree($toJson = false)
    {

        $categories = Category::all()->toArray();
        //dd($categories);
        $parentCategories = [];
        $sonCategories    = [];
        // 获取分类分组为父分类和子分类
        foreach ($categories as $category) {
            if ($category['parent_id'] === 0) {
                $category['sons'] = [];
                $parentCategories[$category['id']] = $category;
            } else {
                $sonCategories[] = $category;
            }
        }
        // 将子分类加入到对应的父分类
        foreach ($sonCategories as $sonCategory) {
            $pid = $sonCategory['parent_id'];
            if ($parentCategories[$pid]) {
                $parentCategories[$pid]['sons'][] = $sonCategory;
            }
        }

        // 返回二层树结构的分类数组
        if ($toJson) {
            return json_encode($parentCategories, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
        }
        return $parentCategories;
    }
}
